package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.ApplicationContext;
import com.itheima.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: 斌
 * @DateTime: 2023年02月06日  10:49:14
 * @Description: com.itheima.filter
 * @Version: 1.0
 */
@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {
    //路径匹配器，final保证多次访问是同一对象
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求路径
        String requestURI = request.getRequestURI();
        log.info("拦截到的请求路径:{}",requestURI);
        //    放行的路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendMsg"};

    //    进行路径匹配校验
       Boolean flag =  check(urls,requestURI);
       if (flag){
           log.info("被放行的路径:{}",requestURI);
           filterChain.doFilter(request,response);
           //路径匹配成功后结束if，继续往下执行
           return;
       }
    //   对是否登录进行校验employee
        if (request.getSession().getAttribute("employee") != null ){
            log.info("当前用户信息:{}",request.getSession().getAttribute("employee"));
            log.info("当前线程信息:{}",ApplicationContext.threadLocal);
            ApplicationContext.setData(request.getSession().getAttribute("employee"));
            filterChain.doFilter(request,response);
            return;
        }
        //   对是否登录进行校验user
        if ( request.getSession().getAttribute("user") != null){

            log.info("当前用户信息:{}",request.getSession().getAttribute("user"));
            log.info("当前线程信息:{}",ApplicationContext.threadLocal);
            ApplicationContext.setData(request.getSession().getAttribute("user"));
            filterChain.doFilter(request,response);
            return;
        }
        String notlogin = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(notlogin);

    }

    public Boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            log.info("被匹配到的路径:{}",url);
            boolean flag = PATH_MATCHER.match(url, requestURI);
            if (flag){
                return true;
            }
        }
        return false;

    }
}
